﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "StructureVariableSectionBeam.h"
#include "BeamStartAndEndOffsetParameterUpdater.h"
#include "DbObjectUtils.h"
#include "GbmpBuiltInParameterDefinitionsNew.h"
#include "GbmpBuiltInParameterStaticVauleListItems.h"
#include "ICalculator.h"
#include "ICalculatorCollection.h"
#include "ICopyStrategyReporter.h"
#include "IDocument.h"
#include "IElement.h"
#include "IElementParameters.h"
#include "IElementParentReporter.h"
#include "IElementPosition.h"
#include "IElementStatus.h"
#include "IExternalDataComponent.h"
#include "IFamily.h"
#include "IInstance.h"
#include "IInstanceType.h"
#include "ILevel.h"
#include "IParameter.h"
#include "IParameterDefinitionLibrary.h"
#include "IPositionCurve2d.h"
#include "IPositionSingleAssociatedPlane.h"
#include "IRegenerator.h"
#include "IRegeneratorDataIdCreator.h"
#include "LevelUtils.h"
#include "StructureBeamInput.h"
#include "StructureBeamPositionPoints.h"
#include "StructureInstanceLevelUtils.h"
#include "StructureInstanceUtils.h"
#include "StructureBeamElementParametersCustomizer.h"

#include "EnableCompileWarning_The_LAST_IncludeInCpp.h"

using namespace gcmp;

IMPLEMENT_REGEN_FUNCTIONS(gcmp, StructureVariableSectionBeam, BottomAngle)

DEFINE_STRUCTURE_INSTANCE_BASE_DATA_METHODS(StructureVariableSectionBeam, BaseData);

DBOBJECT_DATA_DEFINE(StructureVariableSectionBeam)
{
    SetBottomAngle__(0);
}

StructureVariableSectionBeam* StructureVariableSectionBeam::Create(const StructureBeamInput* pInput)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInput, L"pInput为空",L"GDMPLab",L"2024-03-30");

    IInstance* pInstance = nullptr;
    if (pInput->PositionType == ElementInputPositionType::Line)
    {
        pInstance = StructureVariableSectionBeam::CreateStraightBeam(pInput);
    }
    else if (pInput->PositionType == ElementInputPositionType::ArcBy3Points)
    {
        //pInstance = StructureVariableSectionBeam::CreateArcBy3PtsBeam(pInput);
    }
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstance, L"pInstance为空",L"GDMPLab",L"2024-03-30");

    StructureVariableSectionBeam* pVariableSectionBeam = StructureVariableSectionBeam::Get(pInstance);
    return pVariableSectionBeam;
}

IInstance* StructureVariableSectionBeam::CreateStraightBeam(const StructureBeamInput* pInput)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInput, L"pInput为空",L"GDMPLab",L"2024-03-30");

    IDocument* pDoc = pInput->Document;
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDoc, L"pDoc为空",L"GDMPLab",L"2024-03-30");

    IInstanceType* pInstanceType = quick_cast<IInstanceType>(pDoc->GetElement(pInput->InstanceTypeId));
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstanceType, L"pInstanceType为空",L"GDMPLab",L"2024-03-30");

    IInstance* pInstance = pInstanceType->CreateInstance(L"变截面梁实例", pInput->CanBeShared, pInput->CreationOption, pInput->IsCreateGeometryRelationshipComponent);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstance, L"pInstance为空",L"GDMPLab",L"2024-03-30");

    StructureVariableSectionBeam* pBeam = StructureVariableSectionBeam::RegisterExternalData(pInstance, pInput);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pBeam, L"pBeam为空",L"GDMPLab",L"2024-03-30");

    ElementId associatedPlaneId = pInput->AssociatedPlaneId;
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(associatedPlaneId.IsValid(), L"associatedPlaneId无效",L"GDMPLab",L"2024-03-30");

    const ILevel* pStoreyLevel = nullptr;
    if (pInput->StoreyId.IsValid())
    {
        pStoreyLevel = LevelUtils::GetLevelById(pDoc, pInput->StoreyId);
    }
    else
    {
        pStoreyLevel = StructureInstanceLevelUtils::GetBeamStoreyLevelFromPositioningLevel(pDoc, associatedPlaneId);
    }
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pStoreyLevel, L"pStoreyLevel为空",L"GDMPLab",L"2024-03-30");

    bool bOk = StructureInstanceLevelUtils::CreateInstanceStoreyLevel(pInstance, pStoreyLevel);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"SetBeamStoreyLevel失败",L"GDMPLab",L"2024-03-30");

    bOk = IElementPosition::CreateCurve2dOnTopAssociatedPlanePositionBehavior(pInstance, associatedPlaneId, pInput->PositionPoints);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"PositionBehavior创建失败",L"GDMPLab",L"2024-03-30");

    IElementPosition* pPositionBehavior = pInstance->GetElementPosition();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pPositionBehavior, L"pPositionBehavior为空",L"GDMPLab",L"2024-03-30");

    IPositionSingleAssociatedPlane* pPositionSingleAssociatedPlane =
        quick_cast<IPositionSingleAssociatedPlane>(pPositionBehavior->GetPositionAssociatedPlane());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pPositionSingleAssociatedPlane, L"pPositionSingleAssociatedPlane为空",L"GDMPLab",L"2024-03-30");
    pPositionSingleAssociatedPlane->SetOffset(pInput->AssociatedPlaneOffset);

    pInstance->SetPositionPoints(NEW_AS_OWNER_PTR(StructureBeamPositionPoints, pInstance));

    const IPositionCurve2d* pPosCurve2d = dynamic_cast<const IPositionCurve2d*>(pPositionBehavior->GetPositionGeometry());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pPosCurve2d, L"pPosCurve2d为空",L"GDMPLab",L"2024-03-30");
    bOk = pInstance->SetCoordinateSystemsByCurve(pPosCurve2d->GetBaseCurve());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"SetCoordinateSystemsByCurve失败",L"GDMPLab",L"2024-03-30");

    if (pInstance->GetElementParameters())
    {
        OwnerPtr<IElementParametersCustomizer> opNewCustomizer = 
            NEW_AS_OWNER_PTR(StructureBeamElementParametersCustomizer, pInstance);
        GmStructureDefaultElementParametersCustomizer::SetElementParametersCustomizer(
            pInstance, TransferOwnership(opNewCustomizer));
    }

    IElementStatus* pStatus = pInstance->GetStatus();
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pStatus, L"无法获取状态集",L"GDMPLab",L"2024-03-30");
    pStatus->SetIsVisible(pInput->Visible);

    bOk = pDoc->GetRegenerator()->RegenerateElement(pInstance->GetElementId());
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(bOk, L"RegenerateElement失败",L"GDMPLab",L"2024-03-30");

    return pInstance;
}

StructureVariableSectionBeam* StructureVariableSectionBeam::Get(IInstance* pInstance)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstance, L"pInstance为空",L"GDMPLab",L"2024-03-30");
    if (IExternalDataComponent * pExternalDataComponent = pInstance->GetExternalDataComponent())
    {
        IExternalData* pData = pExternalDataComponent->FindExternalData(StructureVariableSectionBeam::GetStaticClassSchema()->GetName());
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pData, L"pData为空",L"GDMPLab",L"2024-03-30");

        return quick_cast<StructureVariableSectionBeam>(pData);
    }
    return nullptr;
}

const StructureVariableSectionBeam* StructureVariableSectionBeam::Get(const IInstance* pInstance)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstance, L"pInstance为空",L"GDMPLab",L"2024-03-30");
    if (const IExternalDataComponent * pExternalDataComponent = pInstance->GetExternalDataComponent())
    {
        const IExternalData* pData = pExternalDataComponent->FindExternalData(StructureVariableSectionBeam::GetStaticClassSchema()->GetName());
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pData, L"pData为空",L"GDMPLab",L"2024-03-30");

        return quick_cast<const StructureVariableSectionBeam>(pData);
    }
    return nullptr;
}

StructureVariableSectionBeam* StructureVariableSectionBeam::RegisterExternalData(IInstance* pInstance, const StructureBeamInput* pInput)
{
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInstance, L"pInstance为空",L"GDMPLab",L"2024-03-30");
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pInput, L"pInput为空",L"GDMPLab",L"2024-03-30");

    OwnerPtr<StructureVariableSectionBeam> opBasicBeam = NEW_AS_OWNER_PTR(StructureVariableSectionBeam);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opBasicBeam, L"opBasicBeam为空",L"GDMPLab",L"2024-03-30");

    OwnerPtr<StructureBeam> opBaseData = StructureBeam::Create(pInstance, pInput);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opBaseData, L"opBaseData为空",L"GDMPLab",L"2024-03-30");
    opBasicBeam->SetBaseData__(TransferOwnership(opBaseData));

    StructureVariableSectionBeam* pBasicBeam = opBasicBeam.get();
    if (IExternalDataComponent * pExternalDataComponent = pInstance->GetExternalDataComponent())
    {
        pExternalDataComponent->RegisterExternalData(StructureVariableSectionBeam::GetStaticClassSchema()->GetName(), TransferOwnership(opBasicBeam));
    }
    return pBasicBeam;
}

BeamZPositioningType StructureVariableSectionBeam::GetZPositioningType() const
{
    // 变截面梁只支持顶部对齐到标高
    return BeamZPositioningType::Top;
}

double StructureVariableSectionBeam::GetVolume() const
{
    return GetBaseData__()->GetVolume();
}

bool StructureVariableSectionBeam::SetVolume(double volume)
{
    return GetBaseDataFW__()->SetVolume(volume);
}

double StructureVariableSectionBeam::GetLength() const
{
    return GetBaseData__()->GetLength();
}

bool StructureVariableSectionBeam::SetLength(double length)
{
    return GetBaseDataFW__()->SetLength(length);
}

void StructureVariableSectionBeam::UpdateForWeakParentDeletion(const std::set<ElementId>& deletedElementIds)
{
    GetBaseDataFW__()->UpdateForWeakParentDeletion(deletedElementIds);
}
void StructureVariableSectionBeam::ReportParents(IElementParentReporter& reporter) const
{
    GetBaseData__()->ReportParents(reporter);
}

DECLARE_CALCULATOR_CREATOR(StructureVariableSectionBeamTopElevationCalculator)
DECLARE_CALCULATOR_CREATOR(StructureVariableSectionBeamStartBottomElevationCalculator)
DECLARE_CALCULATOR_CREATOR(StructureVariableSectionBeamEndBottomElevationCalculator)
DECLARE_CALCULATOR_CREATOR(StructureVariableSectionBeamBottomAngleCalculator)
void StructureVariableSectionBeam::GetCalculators(ICalculatorCollection * calculators) const
{
    GetBaseData__()->GetCalculators(calculators);
    ADD_CALCULATOR(StructureVariableSectionBeamTopElevationCalculator, GetDocument(), GetBaseData__()->GetTopElevationRdId());
    ADD_CALCULATOR(StructureVariableSectionBeamStartBottomElevationCalculator, GetDocument(), GetBaseData__()->GetStartBottomElevationRdId());
    ADD_CALCULATOR(StructureVariableSectionBeamEndBottomElevationCalculator, GetDocument(), GetBaseData__()->GetEndBottomElevationRdId());
    ADD_CALCULATOR(StructureVariableSectionBeamBottomAngleCalculator, GetDocument(), GetBottomAngleRdId());
}

void StructureVariableSectionBeam::ReportParameterDefinitions(std::vector<int>* pParamDefIds) const
{
    GetBaseData__()->ReportParameterDefinitions(pParamDefIds);

    DBG_WARN_AND_RETURN_VOID_UNLESS(pParamDefIds, L"pParamDefIds为空",L"GDMPLab",L"2024-03-30");
    pParamDefIds->push_back(PARAMETER_ID(BeamZPositioningTypeBuiltInParameter));
    pParamDefIds->push_back(PARAMETER_ID(TopElevationBuiltInParameter));
    pParamDefIds->push_back(PARAMETER_ID(StartBottomElevationBuiltInParameter));
    pParamDefIds->push_back(PARAMETER_ID(EndBottomElevationBuiltInParameter));
    pParamDefIds->push_back(PARAMETER_ID(VariableSectionBeamBottomAngleBuiltInParameter));
}

OwnerPtr<IParameter> StructureVariableSectionBeam::GetNativeParameter(int paramDefId) const
{
    OwnerPtr<IParameter> nativeParam = GetBaseData__()->GetNativeParameter(paramDefId);
    if (IParameter::IsValidParameter(nativeParam))
        return nativeParam;

    OwnerPtr<IParameter> param;
    ParameterAttributes pa = {false, false, true};
    if (paramDefId == PARAMETER_ID(BeamZPositioningTypeBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Int, false, false,
            //true, PARAMETER_UID(BeamZPositioningTypeBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Int, pa,
            PARAMETER_UID(BeamZPositioningTypeBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsInt((int)GetZPositioningType());
        return TransferOwnership(param);
    }
    else if (paramDefId == PARAMETER_ID(TopElevationBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Double, false, false,
            //true, PARAMETER_UID(TopElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Double, pa,
            PARAMETER_UID(TopElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsDouble(GetTopElevation());
        return TransferOwnership(param);
    }
    else if (paramDefId == PARAMETER_ID(StartBottomElevationBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Double, false, false,
            //true, PARAMETER_UID(StartBottomElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Double, pa,
            PARAMETER_UID(StartBottomElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsDouble(GetStartBottomElevation());
        return TransferOwnership(param);
    }
    else if (paramDefId == PARAMETER_ID(EndBottomElevationBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Double, false, false,
            //true, PARAMETER_UID(EndBottomElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Double, pa,
            PARAMETER_UID(EndBottomElevationBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsDouble(GetEndBottomElevation());
        return TransferOwnership(param);
    }
    else if (paramDefId == PARAMETER_ID(VariableSectionBeamBottomAngleBuiltInParameter))
    {
        //param = NEW_AS_OWNER_PTR(Parameter, GetDocument(), ParameterStorageType::Double, false, false,
            //true, PARAMETER_UID(VariableSectionBeamBottomAngleBuiltInParameter), ParameterProcessType::GeneralOutput);
        param = IParameter::CreateParameter(GetDocument(), ParameterStorageType::Double, pa,
            PARAMETER_UID(VariableSectionBeamBottomAngleBuiltInParameter), ParameterProcessType::GeneralOutput);
        param->SetValueAsDouble(GetBottomAngle());
        return TransferOwnership(param);
    }

    return nullptr;
}

bool StructureVariableSectionBeam::SetNativeParameter(const IParameter *param, std::wstring* errorMsg/* = nullptr*/)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(param, L"param is null.",L"GDMPLab",L"2024-03-30");

    if (GetBaseDataFW__()->SetNativeParameter(param, errorMsg))
        return true;

    if (param->GetParameterDefinitionId() == PARAMETER_ID(VariableSectionBeamBottomAngleBuiltInParameter))
    {
        SetBottomAngle(param->GetValueAsDouble());
        return true;
    }
    return false;
}

bool StructureVariableSectionBeam::IsParameterModifiable(int paramDefId) const
{
    if (!GetBaseData__()->IsParameterModifiable(paramDefId))
        return false;

    if (paramDefId == PARAMETER_ID(BeamZPositioningTypeBuiltInParameter) ||
        paramDefId == PARAMETER_ID(TopElevationBuiltInParameter) ||
        paramDefId == PARAMETER_ID(StartBottomElevationBuiltInParameter) ||
        paramDefId == PARAMETER_ID(EndBottomElevationBuiltInParameter) ||
        paramDefId == PARAMETER_ID(VariableSectionBeamBottomAngleBuiltInParameter))
    {
        return false;
    }
    return true;
}

void StructureVariableSectionBeam::Report(const ICopyContext & copyContext, ICopyStrategyReporter& reporter) const
{
    GetBaseData__()->Report(copyContext, reporter);
}

bool StructureVariableSectionBeam::SetOwnerElement(IElement* pOwnerElement)
{
    return m_BaseData->SetOwnerElement(pOwnerElement);
}

IElement* StructureVariableSectionBeam::GetOwnerElement()
{
    return m_BaseData->GetOwnerElement();
}

const IElement* StructureVariableSectionBeam::GetOwnerElement() const
{
    return GetBaseData__()->GetOwnerElement();
}

IDocument* StructureVariableSectionBeam::GetDocument() const
{
    return GetBaseData__()->GetDocument();
}

ElementId StructureVariableSectionBeam::GetOwnerElementId() const
{
    return GetBaseData__()->GetOwnerElementId();
}

NdbObject* StructureVariableSectionBeam::GetTopOwnerObject() const
{
    const StructureBeam* pBaseData = GetBaseData__().get();
    if (!pBaseData)
        return nullptr;
    return pBaseData->GetTopOwnerObject();
}
